package org.xiaojun.loginDemo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.xiaojun.loginDemo.model.CaptchaModel;
import org.xiaojun.loginDemo.pojo.User;
import org.xiaojun.loginDemo.mapper.UserMapper;
import org.xiaojun.loginDemo.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xj
 * @since 2021-08-06
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    UserMapper userMapper;

    @Override
    public String regist(String userName, String password, String code, HttpSession session) {

        String msg = null;

        if (StringUtils.isBlank(userName) || StringUtils.isBlank(password)){
            msg = "用户名或密码不能为空";
            return msg;
        }

        User temp = userMapper.queryUserByUserName(userName);

        if (temp != null){
            msg = "用户名已存在";
            return msg;
        }

        CaptchaModel captchaModel = (CaptchaModel) session.getAttribute("code");
        if (captchaModel.isExpired()){
            msg = "验证码超时";
            return msg;
        }
        if (!Objects.equals(captchaModel.getCode(), code)){
            msg = "验证码错误";
            return msg;
        }

        User user = new User();
        user.setUserName(userName);
        user.setPassword(password);
        user.setCreateDate(LocalDateTime.now());
        boolean save = this.save(user);
        if (!save){
            msg = "注册失败";
            return msg;
        }

        return null;
    }

    @Override
    public String login(String userName, String password, String code, HttpSession session) {

        String msg = null;

        if (StringUtils.isBlank(userName) || StringUtils.isBlank(password)){
            msg = "用户名或密码不能为空";
            return msg;
        }

        CaptchaModel captchaModel  = (CaptchaModel) session.getAttribute("code");
        if (captchaModel.isExpired()){
            msg = "验证码已过期";
            return msg;
        }

        if (!Objects.equals(captchaModel.getCode(), code)){
            msg = "验证码错误";
            return msg;
        }

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name", userName).eq("password", password);

        User temp = this.getOne(queryWrapper);
        if (Objects.isNull(temp)){
            msg = "用户名或密码错误";
            return msg;
        }

        session.setAttribute("user", temp);
        return null;

    }


}
